package org.dcat.ums.sdk;

import java.text.SimpleDateFormat;

import org.dcat.ums.sdk.common.Constant;
import org.dcat.ums.sdk.common.NetworkUitlity;
import org.dcat.ums.sdk.common.Utils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

public class DcatAgent {

	private static DcatAgent dcatAgent = new DcatAgent();
	private Handler handler;
	private String appkey;
	private int defaultReportMode = 0;
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private DcatAgent() {
		HandlerThread localHandlerThread = new HandlerThread("DcatAgent");
		localHandlerThread.start();
		this.handler = new Handler(localHandlerThread.getLooper());
	}

	public static DcatAgent getDcatAgent() {
		return dcatAgent;
	}

	public int getDefaultReportMode() {
		return defaultReportMode;
	}

	/**
	 * Setting data transmission mode
	 * 
	 * @param context
	 * @param reportModel
	 */
	public static void setDefaultReportPolicy(Context context, int reportModel) {
		Log.d("reportType", reportModel + "");
		if ((reportModel == 0) || (reportModel == 1)) {

			dcatAgent.defaultReportMode = reportModel;
			String str = context.getPackageName();
			SharedPreferences localSharedPreferences = context.getSharedPreferences("d_agent_online_setting_" + str, 0);
			localSharedPreferences.edit().putInt("ums_local_report_policy", reportModel).commit();
		}
	}

	/**
	 * 统计应用启动次数,启动时间段
	 */
	public void count() {

	}

	/**
	 * 初始化DcatAgent
	 * 
	 * @param context
	 */
	public void init(final Context context, final String deviceType) {
		if (handler != null) {
			handler.post(new Runnable() {

				@Override
				public void run() {
					onInit(context, deviceType);
				}
			});
		}
	}

	private void onInit(Context context, String deviceType) {

		appkey = Utils.getAppKey(context);

		JSONObject updateObject = new JSONObject();

		TelephonyManager tm = (TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE));
		DisplayMetrics displaysMetrics = context.getResources().getDisplayMetrics();
		try {

			updateObject.put("appkey", appkey);
			updateObject.put("deviceType", deviceType);
			updateObject.put("deviceid", tm.getDeviceId());
			updateObject.put("androidid", Utils.getAndroidId(context));
			updateObject.put("osversion", Build.VERSION.RELEASE);
			updateObject.put("model", Build.MODEL);
			updateObject.put("sdkVersion", String.valueOf(Build.VERSION.SDK_INT));
			updateObject.put("manufacturer", Build.MANUFACTURER);
			updateObject.put("fingerprint", Build.FINGERPRINT);
			updateObject.put("resolution", displaysMetrics.widthPixels + "x" + displaysMetrics.heightPixels);
			updateObject.put("createtime", Utils.getTime());
			updateObject.put("imsi", tm.getSubscriberId());
			updateObject.put("noperator", tm.getNetworkOperator());
			updateObject.put("noperatorname", tm.getNetworkOperatorName());
			updateObject.put("network", Utils.getNetworkType(context));
			Log.i("", "=>" + updateObject.toString());
			if (Utils.isNetworkAvailable(context) && Utils.isNetworkTypeWifi(context)) {
				NetworkUitlity.post(Constant.DEVICE_STRING, updateObject.toString());
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private long startMillis;// 进入界面开始时间
	private long endMillis;// 退出界面时间

	public void onCreate(Context context) {
		startMillis = System.currentTimeMillis();
	}

	public void onDestroy(Context context) {
		endMillis = System.currentTimeMillis();
		destroy(context);
	}

	private void destroy(final Context context) {
		if (handler != null) {
			handler.post(new Runnable() {

				@Override
				public void run() {
					postOnDestroy(context);
				}

			});
		}
	}

	private void postOnDestroy(final Context context) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				JSONObject localJSONObject = null;
				try {
					// 收集打开页面信息,时间
					localJSONObject = new JSONObject();
					localJSONObject.put("appkey", appkey);
					localJSONObject.put("context", context.getClass().getSimpleName());
					localJSONObject.put("intime", startMillis);
					localJSONObject.put("outtime", endMillis);
					localJSONObject.put("staytime", endMillis - startMillis);

					if (Utils.isNetworkAvailable(context)) {
						try {
							NetworkUitlity.post(Constant.APP_PAGE_STRING, localJSONObject.toString());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}).start();
	}

	/**
	 * 搜集点击事件信息
	 * 
	 * @param context
	 * @param event_id
	 */
	public void onEvent(final Context context, final String event_id) {
		this.onEvent(context, event_id, null);
	}

	/**
	 * 搜集点击事件信息
	 * 
	 * @param context
	 * @param event_id
	 * @param label
	 */
	public void onEvent(final Context context, final String event_id, final String label) {
		if (handler != null) {
			handler.post(new Runnable() {

				@Override
				public void run() {
					postOnEvent(context, event_id, label);
				}
			});
		}
	}

	private void postOnEvent(final Context context, final String event_id, final String label) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				saveEvent(context, event_id, label);
			}
		}).start();
	}

	private void saveEvent(Context context, String event_id, String label) {
		JSONObject localJSONObject = null;
		try {
			localJSONObject = new JSONObject();
			localJSONObject.put("context", context.getClass().getSimpleName());
			localJSONObject.put("appkey", appkey);
			localJSONObject.put("event_id", event_id);
			localJSONObject.put("label", label);

			if (Utils.isNetworkAvailable(context)) {
				try {
					NetworkUitlity.post("eventUrl", localJSONObject.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
